import poser, os, sys, gzip

sys.path.append( os.path.join("Runtime","Python","PoseWorks","GlowWorm","Data"))

import gwrJob, gwrParse, gwrGui
from gwrVars import *
from gwrXml import *

def writeExecutablePzz( renderJob, outPzz, runSims=0 ):
	outGw6 = os.path.splitext( outPzz )[0] + ".gw6"
	outStr = """{\n\nversion\n\t{\n\tnumber 6\n\t}\ndoc\n\t{\n\tanimSets\n\t\t{\n\t\tanimSet gwoJob\n\t\t\t{\n\t\t\tattrib jobFile\n\t\t\t\t"%s"\n\t\t\tattrib runSims\n\t\t\t\t%i\n\t\t\t}\n\t\t}\n\t}\nrunPythonScript ":Runtime:Python:PoseWorks:GlowWorm:Execute Job.py"\n}""" % (outGw6, runSims)
	zfi = gzip.GzipFile( outPzz, 'wb' )
	zfi.write( outStr )
	zfi.close()
	gwrParse.saveJobAs( renderJob, outGw6 )

def askWritePzz():
	dodir = 1 - poser.DialogSimple.YesNo("Would you like the executable PZZ to render a directory?")
	jm = gwrGui.JobMaker(jobfile="temp.gw6", useFile=dodir)
	if jm.Show():
		outPzz = AskSaveAs(extensions=(".pzz"))
		if outPzz:
			if outPzz[-1] == ".": outPzz = outPzz + "gwo.pzz"
			else: outPzz = outPzz + ".gwo.pzz"
			renderJob = gwrParse.readJob("temp.gw6")
			os.remove("temp.gw6")
			runSims = poser.DialogSimple.YesNo("Run simulations before rendering?")
			writeExecutablePzz( renderJob, outPzz, runSims )

class ExecJob:
	def __init__(self, jobFile, runSims):
		if not os.path.exists( jobFile ):
			raise "ERROR! Render job file missing or moved!\nExpected to find render job file at %s" % jobFile
		self.jobFile = jobFile
		self.jobToRender = gwrParse.readJob(jobFile)
		self.runSims = runSims
	def log(self, s):
		print s
		poser.Scene().Draw()
	def execute(self):
		self.log("Rendering executable job...")
		self.jobMan = gwrJob.jobManager( [self.jobToRender], runSims=self.runSims )
		self.jobMan.finishJob = lambda v=None, s=self: s.log(v)
		try:
			self.jobMan.renderAll()
			self.log("Rendering complete.")
			try:
				os._exit(1)
			except:
				pass
		except gwrJob.excCancelRender:
			self.log("Render canceled by user")
		except:
			info = sys.exc_info()
			ErrorBox("A error has occured.")
			import traceback
			error = "An error occured while rendering:\n\n" + string.join( traceback.format_tb(info[2]) )
			error = error + "\nException Type: %s\n" % sys.exc_type
			error = error + "GlowWorm version: %s\n" % GLOWWORM_VERSION
			error = error + "Operating system: %s\n" % GLOWWORM_PLATFORM
			error = error + "Poser version: %s\n" % poser.Version()
			self.Log(error)
			print error
			print "Please report the entire text of this error to dan.nicho@gmail.com (you can copy and paste.)"
			raise

def execGwoPzz():
	scene = poser.Scene()
	univ = scene.ActorByInternalName("UNIVERSE")
	fx6File = univ.GeomFileName()
	jobAttribs = scene.AnimSet("gwoJob").Attributes()
	jobFile = None
	runSims = 0
	for attrib, value in jobAttribs:
		if attrib == "jobFile":
			jobFile = value
		elif attrib == "runSims":
			runSims = float(value)
	executor = ExecJob( jobFile, runSims )
	executor.execute()

if __name__ == '__main__':
	askWritePzz()

pass
